﻿<%@ WebHandler Language="C#" Class="data" %>


using System;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography;
using LitJson;
using System.Net;

public class data : IHttpHandler
{
    private string _operType = string.Empty;
    private string _response = string.Empty;
    public void ProcessRequest(HttpContext context)
    {
        this._operType = GetQueryString("oper");
        switch (this._operType)
        {
            case "getCodeList":
                getCodeList(context);
                break;
            case "getNCodeList":
                getNCodeList(context);
                break;
            case "getStockInList":
                getStockInList(context);
                break;
            case "getStockOutList":
                getStockOutList(context);
                break;
            default:
                DefaultResponse(context);
                break;
        }
        context.Response.Write(this._response);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private void DefaultResponse(HttpContext context)
    {
        this._response = "{\"status\":0, \"msg\":\"未知操作\"}";
    }

    #region 
    private void getCodeList(HttpContext context)
    {
        string val1 = GetQueryString("val1");
        string val2 = GetQueryString("val2");
        string val3 = GetQueryString("val3");
        string val4 = GetQueryString("val4");
        string val5 = GetQueryString("val5");
        string val6 = GetQueryString("val6");
        string val7 = GetQueryString("val7");
        try
        {
            string strSql = "P_PrintCode '" + val1 + "','" + val2 + "','" + val3 + "','" + val4 + "','" + val5 + "','" + val6 + "','" + val7 + "'";
            ErrorLog(strSql);
            SubSonic.QueryCommand cmd = new SubSonic.QueryCommand(strSql);

            DataSet ds = SubSonic.DataService.GetDataSet(cmd);
            DataTable dt = ds.Tables[0];
            string json = DT2JSON(dt, 0, "total", "result");
            this._response = "{\"status\":\"1\",\"msg\":\"正常\"," + json + "}";
            dt.Clear();
            dt.Dispose();
        }
        catch (Exception ex)
        {
            this._response = "{\"status\":\"0\",\"msg\":\"错误\",\"错误信息\":" + ex + "}";
        }
    }
    #endregion

    #region 
    private void getNCodeList(HttpContext context)
    {
        string label = GetQueryString("label");
        string ids = GetQueryString("ids");
        try
        {
            string strSql = "P_PrintCodeLabel '" + label + "','" + ids + "'";
            ErrorLog(strSql);
            SubSonic.QueryCommand cmd = new SubSonic.QueryCommand(strSql);

            DataSet ds = SubSonic.DataService.GetDataSet(cmd);
            DataTable dt = ds.Tables[0];
            string json = DT2JSON(dt, 0, "total", "result");
            this._response = "{\"status\":\"1\",\"msg\":\"正常\"," + json + "}";
            dt.Clear();
            dt.Dispose();
        }
        catch (Exception ex)
        {
            this._response = "{\"status\":\"0\",\"msg\":\"错误\",\"错误信息\":" + ex + "}";
        }
    }
    #endregion
    #region 
    private void getStockInList(HttpContext context)
    {
        string id = GetQueryString("id");
        try
        {
            string strSql = "P_PrintStockIn '" + id + "'";
            ErrorLog(strSql);
            SubSonic.QueryCommand cmd = new SubSonic.QueryCommand(strSql);

            DataSet ds = SubSonic.DataService.GetDataSet(cmd);
            DataTable dt1 = ds.Tables[0];
            DataTable dt2 = ds.Tables[1];
            string json1 = DT2JSON(dt1, 0, "total", "list");
            string json2 = DT2JSON(dt2, 0, "total", "sublist");
            this._response = "{\"status\":\"1\",\"msg\":\"正常\"," + json1 + "," + json2 + "}";
            dt1.Clear();
            dt1.Dispose();
            dt2.Clear();
            dt2.Dispose();
        }
        catch (Exception ex)
        {
            this._response = "{\"status\":\"0\",\"msg\":\"错误\",\"错误信息\":" + ex + "}";
        }
    }
    #endregion
    #region 
    private void getStockOutList(HttpContext context)
    {
        string id = GetQueryString("id");
        try
        {
            string strSql = "P_PrintStockOut '" + id + "'";
            ErrorLog(strSql);
            SubSonic.QueryCommand cmd = new SubSonic.QueryCommand(strSql);

            DataSet ds = SubSonic.DataService.GetDataSet(cmd);
            DataTable dt1 = ds.Tables[0];
            DataTable dt2 = ds.Tables[1];
            string json1 = DT2JSON(dt1, 0, "total", "list");
            string json2 = DT2JSON(dt2, 0, "total", "sublist");
            this._response = "{\"status\":\"1\",\"msg\":\"正常\"," + json1 + "," + json2 + "}";
            dt1.Clear();
            dt1.Dispose();
            dt2.Clear();
            dt2.Dispose();
        }
        catch (Exception ex)
        {
            this._response = "{\"status\":\"0\",\"msg\":\"错误\",\"错误信息\":" + ex + "}";
        }
    }
    #endregion
    /// <summary>
    /// HTTP POST方式请求数据
    /// </summary>
    /// <param name="url">URL.</param>
    /// <param name="param">POST的数据</param>
    /// <returns></returns>
    public static string HttpPost(string url, string param)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Accept = "*/*";
        request.Timeout = 15000;
        request.AllowAutoRedirect = false;

        StreamWriter requestStream = null;
        WebResponse response = null;
        string responseStr = null;

        try
        {
            requestStream = new StreamWriter(request.GetRequestStream());
            requestStream.Write(param);
            requestStream.Close();

            response = request.GetResponse();
            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            request = null;
            requestStream = null;
            response = null;
        }

        return responseStr;
    }
    #region 将dt转化成Json数据
    /// <summary>
    /// 将dt转化成Json数据
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="fromCount"></param>
    /// <param name="totalCountStr"></param>
    /// <param name="tbname"></param>
    /// <returns></returns>
    public static string DT2JSON(DataTable dt, int fromCount, string totalCountStr, string tbname)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("\"" + totalCountStr + "\":\"" + dt.Rows.Count + "\",\"" + tbname + "\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (i > 0)
                jsonBuilder.Append(",");
            jsonBuilder.Append("{");
            jsonBuilder.Append("\"no\":\"" + (fromCount + i + 1) + "\",");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (j > 0)
                    jsonBuilder.Append(",");
                if (dt.Columns[j].DataType.Equals(typeof(DateTime)) && dt.Rows[i][j].ToString() != "")
                    jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":\"" + Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd HH:mm:ss").Trim() + "\"");
                else if (dt.Columns[j].DataType.Equals(typeof(String)))

                    if (dt.Rows[i][j].ToString().IndexOf("[{") > -1)
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + dt.Rows[i][j].ToString().Trim() + "");
                    else
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":\"" + dt.Rows[i][j].ToString().Trim().Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>").Replace(",", "，").Replace("\"", "'") + "\"");
                else
                {
                    if (dt.Rows[i][j].ToString().IndexOf("[{") > -1)
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + dt.Rows[i][j].ToString().Trim() + "");
                    else
                        jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":\"" + dt.Rows[i][j].ToString().Trim() + "\"");
                }
            }
            jsonBuilder.Append("}");
        }
        jsonBuilder.Append("]");
        return jsonBuilder.ToString();
    }
    #endregion
    #region 获得指定Url参数的值
    /// <summary>
    /// 获得指定Url参数的值
    /// </summary>
    /// <param name="strName">Url参数</param>
    /// <returns>Url参数的值</returns>
    public static string GetQueryString(string strName)
    {
        return GetQueryString(strName, false);
    }

    /// <summary>
    /// 获得指定Url参数的值
    /// </summary> 
    /// <param name="strName">Url参数</param>
    /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
    /// <returns>Url参数的值</returns>
    public static string GetQueryString(string strName, bool sqlSafeCheck)
    {
        if (HttpContext.Current.Request.QueryString[strName] == null)
            return "";

        if (sqlSafeCheck && !IsSafeSqlString(HttpContext.Current.Request.QueryString[strName]))
            return "unsafe string";

        return HttpContext.Current.Request.QueryString[strName];
    }

    /// <summary>
    /// 获得指定表单参数的值
    /// </summary>
    /// <param name="strName">表单参数</param>
    /// <returns>表单参数的值</returns>
    public static string GetFormString(string strName)
    {
        return GetFormString(strName, false);
    }

    /// <summary>
    /// 获得指定表单参数的值
    /// </summary>
    /// <param name="strName">表单参数</param>
    /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
    /// <returns>表单参数的值</returns>
    public static string GetFormString(string strName, bool sqlSafeCheck)
    {
        if (HttpContext.Current.Request.Form[strName] == null)
            return "";

        if (sqlSafeCheck && !IsSafeSqlString(HttpContext.Current.Request.Form[strName]))
            return "unsafe string";

        return HttpContext.Current.Request.Form[strName];
    }

    /// <summary>
    /// 检测是否有Sql危险字符
    /// </summary>
    /// <param name="str">要判断字符串</param>
    /// <returns>判断结果</returns>
    public static bool IsSafeSqlString(string str)
    {
        return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
    }
    #endregion
    #region 保存文件
    /// <summary>
    /// 保存为不带Bom的文件
    /// </summary>
    /// <param name="TxtStr"></param>
    /// <param name="tempDir">格式:a/b.htm,相对根目录</param>
    public static void SaveFile(string TxtStr, string tempDir)
    {
        SaveFile(TxtStr, tempDir, true);
    }
    /// <summary>
    /// 保存文件内容,自动创建目录
    /// </summary>
    /// <param name="TxtStr"></param>
    /// <param name="tempDir">格式:a/b.htm,相对根目录</param>
    /// <param name="noBom"></param>
    public static void SaveFile(string TxtStr, string tempDir, bool noBom)
    {
        try
        {
            //CreateDir(GetFolderPath(true, tempDir));
            System.IO.StreamWriter sw;
            if (noBom)
                sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(tempDir), false, new System.Text.UTF8Encoding(false));
            else
                sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(tempDir), false, System.Text.Encoding.UTF8);

            sw.Write(TxtStr);
            sw.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

    public static void ErrorLog(string mssg)
    {
        string FilePath = HttpContext.Current.Server.MapPath("~/log/webErrorLog.txt");

        try
        {
            if (File.Exists(FilePath))
            {
                using (StreamWriter tw = File.AppendText(FilePath))
                {
                    tw.WriteLine(DateTime.Now.ToString() + "> " + mssg);
                }  //END using

            }  //END if
            else
            {
                TextWriter tw = new StreamWriter(FilePath);
                tw.WriteLine(DateTime.Now.ToString() + "> " + mssg);
                tw.Flush();
                tw.Close();
                tw = null;
            }  //END else

        }  //END Try
        catch (Exception ex)
        { } //END Catch   

    }  // END ErrorLog



    public string httpGet(string url)
    {
        WebClient client = new WebClient();
        client.Credentials = System.Net.CredentialCache.DefaultCredentials;
        client.Encoding = System.Text.Encoding.UTF8;
        string result = client.DownloadString(url);
        return result;
    }
}